<?php
	require '../include/library.inc.php';
	require '../include/admin_login.inc.php';

$sql_lang = 'SELECT lang_id,Name,code FROM language WHERE published ';

if (!isset($_POST['is_submitted'])) {
	$_POST['is_submitted'] = '';
}
if (!isset($error_message)) {
	$error_message = '';
}	


if($_POST["redirect"] || $_SESSION['redirect'] ){
	if($_POST["redirect"]) $redirect = $_POST["redirect"];
	if($_SESSION['redirect']){ 
	$redirect = $_SESSION['redirect'];
	unset($_SESSION['redirect']);
	}
}else{
       $redirect = $_SERVER['HTTP_REFERER'];	
     }	
	 
	
	if ($_POST['is_submitted']) {
		$error_message = '';
		$redirect = $_POST["redirect"];
    
	$result_lang = query($sql_lang);
	while ($row_lang = mysql_fetch_object($result_lang)) {
	
		if (!$_POST['title'][$row_lang->lang_id])  $error_message .= 'Не е въведено заглавие на '.$row_lang->Name.'<br/>';
		
		
		
	
	}
	
	require "../include/image_allowed_type.inc.php";
		
	if (!$_FILES['cover']['name']) $error_message .= 'Не е избрана малка снимка<br/>';
	if(!array_search($_FILES['image']['type'], $allowed_types) && $_FILES['image']['name']) $error_message .= 'Форматът на малката снимка не е позволен<br/>';
	
	/*$size = getimagesize($_FILES['cover']['tmp_name']);
	if ($size[0]!== BIG_WIDTH) $error_message .= 'Широчината на снимката не е точно '.BIG_WIDTH.' пиксела!<br/>';
	if ($size[1]!== BIG_HEIGHT) $error_message .= 'Височината на снимката не е точно '.BIG_HEIGHT.' пиксела!<br/>';
	*/
	
	
    if(!$error_message) {
		
		$sql = "SELECT MAX(order_number)+1 AS order_number FROM products WHERE type = 'product' ";
		$row_number = mysql_fetch_assoc(query($sql));
		
		//Създаваме проекта
		$sql = "INSERT INTO products
				  (published,type, order_number,creation_time,video,coor)
				VALUES
				  ('".intval($_POST['published'])."','product', '".$row_number['order_number']."', 
				   NOW() , '".escape($_POST['video'])."','".escape($_POST['coor'])."')";
		
		query($sql);
		$id = mysql_insert_id();
		
		$result_lang = query($sql_lang);
		$lang_num = 0;
		while ($row_lang = mysql_fetch_object($result_lang)) {
			
			$sql = "INSERT INTO product_description
				  (product_id, lang_id, title, description, meta_key, meta_description)
				VALUES
				  ('".$id."',
				  '".$row_lang->lang_id."', 
				  '".escape($_POST['title'][$row_lang->lang_id])."', 
				  '".escape($_POST['description'][$row_lang->lang_id])."', 
				  '".escape($_POST['meta_key'][$row_lang->lang_id])."',
				  '".escape($_POST['meta_description'][$row_lang->lang_id])."')";
				 
			query($sql);
			
			//$sql = "SELECT id FROM sef_url WHERE sef_url = '".$_POST['sef_url'][$row_lang->lang_id]."' ";
			$sql = "INSERT INTO sef_url
				  ( lang_id, tamplate, query, sef_url)
				VALUES
				  ('".$row_lang->lang_id."', 
				  'product', 
				  '".$id."',
				  'product".$id."')";
				 
			query($sql);
			
			$lang_num++;
		}
		
		
		if($_POST['category_id'])
		{
			$category_id = $_POST['category_id'];
		  
			foreach ($category_id as $key => $value) {
			
				$sql = 'INSERT INTO product_to_category
							  (product_id,category_id)
							VALUES
							  ('.$id.','.intval($value).')
							  ';
				query($sql);
			
			}
		}
		
		
		
		$upload_path = "../product_images/";
		
		if (is_uploaded_file($_FILES['cover']['tmp_name'])) {
			$tmp_file = $_FILES['cover']['tmp_name'];
			$exp = explode('.',$_FILES['cover']['name']);
			$img_type = strtolower(end($exp));
			$new_name = "image".$id.".".$img_type;
			
			
			if(!copy($tmp_file, $upload_path.'big/'.$new_name)) {
				
				$_SESSION['message'] .= 'Грешка при качване на снимка. ';
			}
			
			include '../include/image_man.php';
			$imn = new ImageManipulator;
			$imn -> decider($img_type,$tmp_file);
			
			if(copy($tmp_file.'_image', $upload_path.'medium/'.$new_name) && copy($tmp_file.'_thumb', $upload_path.'covers/'.$new_name)) {
				
				$sql = "UPDATE products SET
							cover = '$new_name'
						WHERE product_id = '$id'";
				query($sql);
				
			} else{
				$_SESSION['message'] .= 'Грешка при качване на снимка. ';
			}
		}
		
		$_SESSION['message'] .= 'Проектът е добавен успешно!';
        if($_POST["redirectForm"]){
            
            redirect($_POST["redirectForm"]);
            
		}else{
            
			$_SESSION['redirect'] = $redirect;
            redirect(HTML_BASE_ADMIN.'product_edit.php?product_id='.$id);
		   
		}
    }

}
  	
	
	head_admin("Добавяне на продукт");
?>

<script type="text/javascript" src="<?=HTML_BASE_ADMIN?>js/calendarDateInput.js"></script>
<script type="text/javascript" src="<?=HTML_BASE_ADMIN?>tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
	// General options
	language : "bg", 
	mode : "exact",
    elements : "body1,body2,body3,body4,body5",
	theme : "advanced",
	relative_urls : false,
	plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager",

	// Theme options
	theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect",
	theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
	theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen,|,image,insertimage",
	theme_advanced_toolbar_location : "top",
	theme_advanced_toolbar_align : "left",
	theme_advanced_statusbar_location : "bottom",
	theme_advanced_resizing : false,	
});
</script>
		
            <?php if ($error_message) { ?>
			<div class="message red">
				<h3>Грешка!</h3>
				<?=$error_message?>
			</div>
			<?php } ?>
			
            <div class="topbuttons">
            	<a href="<?=$redirect?>">Обратно</a>
            </div>
			
            <h3>Добавяне на продукт</h3>
			            
        	<form id="page_new_form_id" action="<?=$_SERVER['PHP_SELF']?>" method="post" enctype="multipart/form-data">
            <input type="hidden" name="is_submitted" value="1" />
			<input type="hidden" name="redirect" value="<?=$redirect?>" />
             <input id="redirectForm" type="hidden" name="redirectForm" value="" />
            <input type="hidden" name="redirect" value="<?=$redirect?>" />						
			
            		
			
			
	<div id="tabs">
   
        
        	<ul id="tabs-ui">
           
			</ul>
			
			
			<?php
			$tabs="";
			$result_lang = query($sql_lang);
			while ($row_lang = mysql_fetch_object($result_lang)) {
				
		     $tabs.=' <li><a href="'.$_SERVER['PHP_SELF'].'#tabs-'.$row_lang->lang_id.'">'.$row_lang->Name.'</a></li>';					  
			?>
           
		<div id="tabs-<?=$row_lang->lang_id?>">
           
                <h3>Данни на  <?=$row_lang->Name?></h3>
                
                
                
                
                <dt><label class="required">Заглавие:</label></dt>
                <dd><input class="inputbox w500"  name="title[<?=$row_lang->lang_id?>]" type="text" value="<?=$_POST['title'][$row_lang->lang_id]?>" ></dd>
                
                <dt><label >Подзаглавие:</label></dt>
                <dd><textarea id="title_<?=$row_lang->lang_id?>" class="inputbox w500" name="meta_description[<?=$row_lang->lang_id?>]" rows="3" maxlength="110"><?=$_POST['meta_description'][$row_lang->lang_id]?></textarea></dd>
                
                
                <dt><label>Описание:</label></dt>
                <dd><textarea id="body<?=$row_lang->lang_id?>"  class="inputbox" style="width:100%" name="description[<?=$row_lang->lang_id?>]" rows="16"><?=sth($_POST['description'][$row_lang->lang_id])?></textarea></dd>
                
                
            
           </div>
            
           <?php
				
			}
			
	  		?>
          
           </div>
    	<dl class="clearfix" >
            
                <dt>
                    <label class="required">Снимка на продукта
                    </label>
                </dt>
                <dd>
                    <input class="inputbox w250" name="cover" type="file" accept="image/*" />
                </dd>
            
            	
           </dl>
        
        <dl class="clearfix" >	
        
        	
			<dd>
			    <input class="checkbox" name="published" id="published" type="checkbox" value="1" <?=(($_POST['published'])?"checked=\"checked\"":"")?> />
				<label>Публикуван</label>
            </dd>
            
            
            
            
            <dt>
      			<h3>Категории</h3>
    		</dt>
    		
            <dd>
				<ul class="type-box">
				<?php
				$_SESSION['i'] = 1;
				function getCategory($parent,$parent_id){         
                    $sql_c = "SELECT
                    c.category_id,
                    d.Name
                    
                FROM
                    category AS c,
                    category_description AS d
                WHERE
                
                    c.category_id = d.category_id
                    
                    AND
                    
                    d.lang_id = '1'
                    
                    AND
                    c.published
					
					AND parent_id = '".$parent_id."'
                    
                    ORDER BY c.order_number 
                    
                  ";
                
                    $result_c = query($sql_c);
                    
                    while ($row = mysql_fetch_object($result_c)) {
                          ?>
                        <li>
                          <label>
                            <input class="checkbox" name="category_id[<?=$_SESSION['i']?>]" type="checkbox" value="<?=$row->category_id?>" 
                                        <?php if($_POST["category_id"]){?>
                                         <?=((in_array( $row->category_id , $_POST["category_id"]))?"checked=\"checked\"":"")?> <?php } ?>/>
                          	<?php if($parent){ 
							echo $parent.' > '.sth($row->Name);
							 } else{ 
							 echo sth($row->Name) ;
							 }?>
                          </label>
                        </li>
        			<?php $_SESSION['i']++;
					
					
						getCategory($parent.' > '.sth($row->Name),$row->category_id);
					} 
					
				} 
				getCategory('',0);
				?>
				
                </ul>
			</dd> 
            
            
		</dl>
                
           
           
	</form>    
            
            
            <script>
	$(document).ready(function(e) {
           $("#tabs-ui").html('<?=$tabs?>');
				
	       $( "#tabs" ).tabs();
	  
      });		
					
  </script>
            
            
<?php
	controls($redirect, "#page_new_form_id");
	foot_admin(); 
?>